<template>
    <div class="approve-profile-page">
        <el-card>
            <h2 style="text-align: center; margin-bottom: 24px">
                主页信息审批
            </h2>
            <div
                style="
                    display: flex;
                    gap: 16px;
                    align-items: center;
                    margin-bottom: 16px;
                "
            >
                <!-- 搜索申请人 -->
                <el-input
                    v-model="searchName"
                    placeholder="搜索申请人"
                    clearable
                    style="width: 200px"
                />
                <!-- 筛选状态 -->
                <el-select
                    v-model="filterStatus"
                    placeholder="筛选状态"
                    clearable
                    style="width: 150px"
                >
                    <el-option label="全部" value="" />
                    <el-option label="待审批" value="待审批" />
                    <el-option label="已通过" value="已通过" />
                    <el-option label="未通过" value="未通过" />
                </el-select>
            </div>
            <el-table :data="pagedApprovals" style="width: 100%">
                <el-table-column
                    prop="userId.name"
                    label="申请人"
                    width="120"
                />
                <el-table-column prop="newImageUrl" label="新图片" width="120">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.newImageUrl"
                            :src="scope.row.newImageUrl"
                            style="width: 4rem; height: 6rem"
                            fit="contain"
                            :preview-src-list="[scope.row.newImageUrl]"
                            preview-teleported
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="newVideoUrl" label="新视频" width="280">
                    <template #default="scope">
                        <video
                            v-if="scope.row.newVideoUrl"
                            :src="scope.row.newVideoUrl"
                            style="width: 16rem"
                            controls
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                        <el-tag
                            :type="
                                scope.row.status === '已通过'
                                    ? 'success'
                                    : scope.row.status === '未通过'
                                    ? 'danger'
                                    : 'info'
                            "
                        >
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="150" />
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button
                            size="small"
                            type="success"
                            @click="openApprove(scope.row, '已通过')"
                            :disabled="
                                scope.row.status === '未通过' ||
                                scope.row.status === '已通过'
                            "
                            round
                            >通过</el-button
                        >
                        <el-button
                            size="small"
                            type="danger"
                            @click="openApprove(scope.row, '未通过')"
                            :disabled="
                                scope.row.status === '未通过' ||
                                scope.row.status === '已通过'
                            "
                            round
                            >拒绝</el-button
                        >
                        <el-popconfirm
                            title="确定删除该申请吗？"
                            @confirm="handleDelete(scope.row)"
                            confirm-button-text="删除"
                            cancel-button-text="取消"
                        >
                            <template #reference>
                                <el-button size="small" type="warning" round
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; margin: 24px 0">
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :page-size="pageSize"
                    :total="approvals.length"
                    v-model:current-page="currentPage"
                />
            </div>
        </el-card>
        <!-- 审批对话框，添加主页数据相关字段 -->
        <el-dialog v-model="showDialog" title="审批说明" width="900px" center>
            <el-form>
                <el-form-item label="审批说明">
                    <el-input
                        v-model="remark"
                        type="textarea"
                        placeholder="请输入审批说明"
                    />
                </el-form-item>
                <!-- 只有“通过”时显示主页数据字段 -->
                <template v-if="approveStatus === '已通过'">
                    <el-form-item label="新名称">
                        <el-input v-model="approveRow.newName" />
                    </el-form-item>
                    <el-form-item label="新图片链接">
                        <el-input v-model="approveRow.newImageUrl" />
                    </el-form-item>
                    <el-form-item label="新视频链接">
                        <el-input v-model="approveRow.newVideoUrl" />
                    </el-form-item>
                    <el-form-item label="（越大图片越往右）">
                        <el-input-number v-model="approveRow.left" :min="0" />
                    </el-form-item>
                    <el-form-item label="（越大图片越往下）">
                        <el-input-number v-model="approveRow.top" :min="0" />
                    </el-form-item>
                    <el-form-item label="（图片宽度）">
                        <el-input-number v-model="approveRow.width" :min="0" />
                    </el-form-item>
                    <el-form-item label="（图片高度）">
                        <el-input-number v-model="approveRow.height" :min="0" />
                    </el-form-item>
                    <el-form-item label="（越大名字越往上）">
                        <el-input-number
                            v-model="approveRow.nameTop"
                            :min="0"
                        />
                    </el-form-item>
                    <el-form-item label="（越小名字越往左）">
                        <el-input-number v-model="approveRow.nameRight" />
                    </el-form-item>
                    <el-form-item label="（名字背景的宽度）">
                        <el-input-number
                            v-model="approveRow.nameBgImgWidht"
                            :min="0"
                        />
                    </el-form-item>
                    <el-form-item
                        label="（名字背景的高度，推荐数值：两字2，三字5，四字7，5字8，六字9）"
                    >
                        <el-input-number
                            v-model="approveRow.nameBgImgHeight"
                            :min="0"
                        />
                    </el-form-item>
                    <el-form-item label="Layers（数字越大，图层越高）">
                        <el-input-number v-model="approveRow.Layers" :min="0" />
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <el-button @click="showDialog = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleApprove"
                    :loading="loading"
                    >确定</el-button
                >
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
    getAllHomeApprovals,
    updateHomeApproval,
    deleteHomeApproval,
    addHomeData,
} from "./api";

const approvals = ref([]);
const searchName = ref("");
const filterStatus = ref("");
const currentPage = ref(1);
const pageSize = 5;

const filteredApprovals = computed(() => {
    return approvals.value.filter((item) => {
        const matchName = searchName.value
            ? (item.userId?.name || "").includes(searchName.value)
            : true;
        const matchStatus = filterStatus.value
            ? item.status === filterStatus.value
            : true;
        return matchName && matchStatus;
    });
});
const pagedApprovals = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return filteredApprovals.value.slice(start, start + pageSize);
});

const showDialog = ref(false);
const remark = ref("");
const loading = ref(false);
const approveRow = ref({
    newName: "",
    newImageUrl: "",
    newVideoUrl: "",
    left: 0,
    top: 0,
    width: 12,
    height: 23,
    nameTop: 10,
    nameRight: -4,
    nameBgImgWidht: 2,
    nameBgImgHeight: 7,
    Layers: 0,
});
const approveStatus = ref("");

const operatorId = sessionStorage.getItem("user_id");

function fetchApprovals() {
    getAllHomeApprovals().then((res) => {
        approvals.value = res;
        currentPage.value = 1;
    });
}

function openApprove(row, status) {
    approveRow.value = Object.assign(
        {
            newName: "",
            newImageUrl: "",
            newVideoUrl: "",
            left: 0,
            top: 0,
            width: 12,
            height: 23,
            nameTop: 10,
            nameRight: -4,
            nameBgImgWidht: 2,
            nameBgImgHeight: 7,
            Layers: 0,
        },
        row
    );
    approveStatus.value = status;
    remark.value = "";
    showDialog.value = true;
}

function handleApprove() {
    loading.value = true;
    // 只有“通过”时才调用 homeData 接口
    if (approveStatus.value === "已通过") {
        const row = approveRow.value;
        // 这里需要根据实际情况填写 left、top、width、height 等参数
        // 你可以让审批人填写，或用默认值
        const homeData = {
            operatorId,
            img: row.newImageUrl,
            video: row.newVideoUrl,
            name: row.newName,
            left: row.left || 0,
            top: row.top || 0,
            width: row.width || 12,
            height: row.height || 23,
            nameTop: row.nameTop || 10,
            nameRight: row.nameRight || -4,
            nameBgImgWidht: row.nameBgImgWidht || 2,
            nameBgImgHeight: row.nameBgImgHeight || 7,
            Layers: row.Layers || 0,
        };
        addHomeData(homeData)
            .then(() => {
                // 添加成功后再更新审批状态
                return updateHomeApproval(row._id, {
                    status: approveStatus.value,
                    remark: remark.value,
                    operatorId,
                });
            })
            .then((res) => {
                ElMessage.success(res.message);
                showDialog.value = false;
                fetchApprovals();
            })
            .catch((err) => {
                ElMessage.error(err.response?.data?.error || "操作失败");
            })
            .finally(() => {
                loading.value = false;
            });
    } else {
        // 非“通过”时，直接更新审批状态
        updateHomeApproval(approveRow.value._id, {
            status: approveStatus.value,
            remark: remark.value,
            operatorId,
        })
            .then((res) => {
                ElMessage.success(res.message);
                showDialog.value = false;
                fetchApprovals();
            })
            .catch((err) => {
                ElMessage.error(err.response?.data?.error || "审批失败");
            })
            .finally(() => {
                loading.value = false;
            });
    }
}

function handleDelete(row) {
    deleteHomeApproval(row._id, { operatorId })
        .then((res) => {
            ElMessage.success(res.message);
            fetchApprovals();
        })
        .catch((err) => {
            ElMessage.error(err.response?.data?.error || "删除失败");
        });
}

onMounted(fetchApprovals);
</script>

<style scoped>
.approve-profile-page {
    padding: 32px 0;
    display: flex;
    justify-content: center;
}
</style>